package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName WebSecurityConfig
 * @Description 此类描述:
 * @Author dangchen
 * @DateTime 2022-08-30 20:09
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity //是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启controller方法权限控制
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /*@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("");
    }*/

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);//必须调用父类的方法，否则就不需要认证即可访问
        //http.headers().frameOptions().sameOrigin();//允许iframe显示

        //允许iframe嵌套显示
        http.headers().frameOptions().sameOrigin();
        //登录设置
        http.authorizeRequests().antMatchers("/static/**","/loginPage").permitAll()//允许匿名用户访问的路径
        .anyRequest().authenticated(); //其他页面全部需要验证

        //自定义登录页面
        http.formLogin()
            .loginPage("/loginPage")//表单页面的地址 IndexController拦截/loginPage转发到frame/login.html
            //.usernameParameter("username")//如果省略,login.html用户名表单项必须是username
            //.passwordParameter("password")//如果省略,必须是password
            .loginProcessingUrl("/login")//login.html提交表单的处理地址
            .defaultSuccessUrl("/");//登录成功后,跳首页
        //自定义注销页面
        http.logout()
            .logoutUrl("/logout")//退出登录的路径,frame/index.html中注销的提交路径
            .logoutSuccessUrl("/loginPage")//用户退出后要被重定向的url
                .invalidateHttpSession(true);
        //如果自定义注销功能,必须禁用csrf
        http.csrf().disable();//关闭跨域请求伪造功能

        //添加自定义无权限处理器
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler());
    }
}
